import React, { useState, useEffect, useRef } from "react"
import { Button, Form, Input, Typography, Image } from "antd"
import {
  UserOutlined,
  LockOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  KeyOutlined
} from "@ant-design/icons"
import { connect } from "react-redux"

import "./Login.less"
import { login } from "../../store/actions"
import { useNavigate } from "react-router-dom"
import { reqCode } from "@/api"
import cookies from "@/utils/cookies"

const { Title } = Typography
const mapStateToProps = (store) => ({ ...store.user })
const mapDispatchToProps = {
  login,
}

function Login(props) {
  const { login } = props
  const [size] = useState("large")
  const [codeImg, setCodeImg] = useState("")
  const [key, setKey] = useState("")
  const navigate = useNavigate()
  const codeEl = useRef()
  const getReqCode = () => {
    reqCode().then((res) => {
      setCodeImg(res.base64)
      setKey(res.key)
    })
  }
  const onFinish = (values) => {
    values.key = key
    login(values, navigate).catch(() => {
      getReqCode()
      setTimeout(() => {
        codeEl.current.focus()
      }, 1000)
    })
  }
  useEffect(() => {
    // 相当于组件挂载和组件更新生命周期钩子
    getReqCode()
    const token = cookies.get("react-token")
    if (token) {
      navigate("/admin", {
        replace: true,
      })
    }
    return () => {
      // 相当于卸载组件的生命周期
    }
  }, [navigate])

  // const validatorpwd = (rule, value) => {
  //   console.log("rule", rule)
  //   console.log("value", value)
  //   // console.log("callback", callback)
  //   if (!value) {
  //     // callback("请输入密码")
  //     return false
  //   } else if (value.length < 4) {
  //     // callback("密码不能小于4位")
  //     return false
  //   } else if (value.length > 12) {
  //     return false
  //     // callback("密码不能大于12位")
  //   } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
  //     // callback("密码必须由英文、数字、下划线组成")
  //     return false
  //   } else {
  //     // callback()
  //     return true
  //   }
  // }
  return (
    <div className="login">
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        layout="vertical"
      >
        <Title>用户登录login...</Title>
        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: "请输入账号",
            },
            {
              pattern: new RegExp(/^[\u4e00-\u9fa5a-zA-Z0-9]{4,12}$/, "g"),
              message: "账号输入不正确,请输入4-12位账号",
            },
          ]}
          // label="账号"
        >
          <Input
            prefix={<UserOutlined className="site-form-item-icon" />}
            placeholder="请输入账号"
            size="large"
          />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: "请输入密码",
              // validator: validatorpwd,
            },
            {
              pattern: new RegExp(
                //   /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{4,16}$/
                /^[a-zA-Z0-9_]{4,16}$/,
                "g"
              ),
              message: "至少4-16个字符，由英文、数字、下划线组成",
            },
          ]}
          // label="密码"
        >
          <Input.Password
            iconRender={(visible) =>
              visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
            }
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="请输入密码"
            size="large"
          />
        </Form.Item>
        <Form.Item
          name="code"
          rules={[
            {
              required: true,
              message: "请输入验证码",
            },
          ]}
        >
          <div className="code">
            <Input
              ref={codeEl}
              key={codeImg}
              prefix={<KeyOutlined className="site-form-item-icon" />}
              type="code"
              placeholder="请输入验证码"
              size="large"
            />
            {codeImg ? (
              <Image
                onClick={getReqCode}
                preview={false}
                src={codeImg}
                width={180}
                height={40}
              />
            ) : null}
          </div>
        </Form.Item>

        {/* <Form.Item>
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>记住我</Checkbox>
          </Form.Item>
        </Form.Item> */}

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            className="login-form-button w100"
            size={size}
            shape="round"
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
export default connect(mapStateToProps, mapDispatchToProps)(Login)
